// 
use anyhow::{anyhow, Result};
use std::net::SocketAddr;
use crate::web_rtc;

pub fn generate_sdp(mime_type: &str, payload_type: u8) -> Result<String> {
    let video_addr = web_rtc::video_addr;
    let audio_addr = web_rtc::audio_addr;
    let (media_type, port, rtpmap, extra) = match mime_type {
        // 视频编码器
        "video/H264" => (
            "video",
            video_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} H264/90000", payload_type),
            ""
        ),
        "video/H265" => (
            "video",
            video_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} H265/90000", payload_type),
            ""
        ),
        "video/VP8" => (
            "video",
            video_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} VP8/90000", payload_type),
            ""
        ),
        "video/VP9" => (
            "video",
            video_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} VP9/90000", payload_type),
            ""
        ),
        "video/AV1" => (
            "video",
            video_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} AV1/90000", payload_type),
            ""
        ),

        // 音频编码器
        "audio/opus" => (
            "audio",
            audio_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} opus/48000/2", payload_type),
            "a=fmtp:111 maxaveragebitrate=64000;minptime=10;useinbandfec=1"
        ),
        "audio/PCMU" => (
            "audio",
            audio_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} PCMU/8000", payload_type),
            ""
        ),
        "audio/PCMA" => (
            "audio",
            audio_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} PCMA/8000", payload_type),
            ""
        ),
        "audio/G722" => (
            "audio",
            audio_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} G722/8000", payload_type),
            ""
        ),
        "audio/MP4A-LATM" => (
            "audio",
            audio_addr.parse::<SocketAddr>()?.port(),
            format!("a=rtpmap:{} MP4A-LATM/44100/2", payload_type),
            "a=fmtp:97 profile-level-id=1;object=2;bitrate=128000"
        ),

        // 不支持的编码器
        _ => {
            println!("⚠️ 不支持的编码格式: {}", mime_type);
            return Err(anyhow!("⚠️ 不支持的编码格式: {}", mime_type));
        }
    };

    let sdp = format!(
        "v=0\r\n\
        o=- 0 0 IN IP4 127.0.0.1\r\n\
        s=Auto SDP\r\n\
        c=IN IP4 127.0.0.1\r\n\
        t=0 0\r\n\
        m={} {} RTP/AVP {}\r\n\
        {}\r\n\
        {}\r\n",
        media_type,
        port,
        payload_type,
        rtpmap,
        extra
    );
    return Ok(sdp);
}